<?php

namespace app;

use libs\HttpRequest;

class QueryIP
{
    const ip_api_url = "http://apis.baidu.com/apistore/iplookupservice/iplookup";

    public static function query($ip)
    {
        $date = false;
        if (self::verifyIP($ip)) {
            if (self::selectMysql($ip)) {
                $date = self::selectMysql($ip);
                $date['msg'] = "本数据由数据库提供！";
            } else {
                $res = HttpRequest::request(self::ip_api_url, ['ip' => $ip], ["apikey:aca5fdb7c77f2eba00027ff9114fd989"]);
                $date = self::formatDate($res);
                $date = $date['retData'];
                $date['msg'] = "本数据由API提供！";
                self::insertMysql($date);
            }
        }
        return $date;
    }

    public static function verifyIP($ip)
    {
        $ret = false;
        if ($ip) {
            $pattern = '/^((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))$/';
            if (preg_match($pattern, $ip)) {
                $ret = true;
            }
        }
        return $ret;
    }

    public static function selectMysql($ip)
    {
        //建立与mysql的连接
        $mysqli = new \mysqli(db_server, db_username, db_password, db_datebasename);
        if ($mysqli->connect_errno) {
            die('连接数据库出错：' . $mysqli->connect_error);
        }

        //设置默认编码
        $mysqli->set_charset('utf8');

        // 选取数据
        $result = $mysqli->query("SELECT * FROM api.ip WHERE ip='{$ip}'");
        $row = $result->fetch_assoc();
        return $row;

    }

    public static function formatDate($date)
    {
        $ret = false;
        if ($date) {
            $ret = json_decode($date, true);
        }
        return $ret;
    }

    public static function insertMysql($date)
    {
        //建立与mysql的连接
        $mysqli = new \mysqli(db_server, db_username, db_password, db_datebasename);
        if ($mysqli->connect_errno) {
            die('连接数据库出错：' . $mysqli->connect_error);
        }

        //设置默认编码
        $mysqli->set_charset('utf8');

        date_default_timezone_set("Asia/Shanghai"); // 指定时区
        $time = date('y-m-d H:i:s', time()); // 获取时间

        //插入记录
        $sql = "INSERT INTO api.ip(ip,country,province,city,district,carrier,datetime)VALUES(
'{$date['ip']}',
'{$date['country']}',
'{$date['province']}',
'{$date['city']}',
'{$date['district']}',
'{$date['carrier']}',
'{$time}'
)";
        if ($mysqli->query($sql)) {
            return true;
        } else {
            return false;
        }

    }

}